package com.yhsoft.benefitcard.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.benefitcard.controller.request.AddCardBatch2InVo;
import com.yhsoft.benefitcard.entity.CardsBatch2;
import com.yhsoft.benefitcard.mapper.CardsBatch2Mapper;
import com.yhsoft.benefitcard.service.ICardsBatch2Service;
import com.yhsoft.common.service.TokenService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 福利卡二级批次信息表 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-10-04
 */
@Service
public class CardsBatch2ServiceImpl extends ServiceImpl<CardsBatch2Mapper, CardsBatch2> implements ICardsBatch2Service {

    @Override
    public void addBatch2(AddCardBatch2InVo inVo, String firstBatchNum, String secondBantchNum, Integer num) {
        // 号段
        Integer num2 = num + Integer.parseInt(inVo.getActivateNum());
        num = num + 1;
        // 设置基础信息
        CardsBatch2 cardsBatch2 = new CardsBatch2();
        cardsBatch2.setFirstBatchNum(firstBatchNum);
        cardsBatch2.setSecondBantchNum(secondBantchNum);
        cardsBatch2.setCardType(inVo.getCardType());
        cardsBatch2.setDistributorId(TokenService.getUserBytoken().getCompanyId());
        cardsBatch2.setFaceValue(inVo.getFaceValue());
        cardsBatch2.setSalePrice(inVo.getSalePrice());
        cardsBatch2.setCustomerId(inVo.getCustomerId());
        cardsBatch2.setEnableCity(inVo.getEnableCitys());
        // 有效期
        if (inVo.getEndTime() == null) {
            cardsBatch2.setIsLimitedDate(0);
        } else {
            cardsBatch2.setIsLimitedDate(1);
            cardsBatch2.setStartTime(inVo.getStartTime());
            cardsBatch2.setEndTime(inVo.getEndTime());
        }

        cardsBatch2.setIsFlimFk(inVo.getIsFlimFk());
        cardsBatch2.setIsSpecialShowing(inVo.getIsSpecialShowing());
        cardsBatch2.setSalesTopicId(inVo.getSalesTopicId());
        cardsBatch2.setIsShowFacevalue(inVo.getIsShowFacevalue());
        if(inVo.getCardType().equals("DYQ")){
            cardsBatch2.setFlimBatchAddPrice(BigDecimal.ZERO);
        }
        // 设置号段
        cardsBatch2.setParagraphNumber(num + "~" + num2);
        // 1-正常，0-冻结
        cardsBatch2.setIsEnable(1);

        this.baseMapper.insert(cardsBatch2);
    }

    @Override
    public void export(String batch1Num, HttpServletResponse response) {
        try {
            List<CardsBatch2> list = this.baseMapper.selectList(Wrappers.<CardsBatch2>lambdaQuery().like(CardsBatch2::getFirstBatchNum, batch1Num));
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("应收账款详情报表");
            //创立标题行
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"id", "二级批次编号", "一级批次编号", "卡片类型", "渠道商ID", "面值","售价","可用城市","开始日期","结束日期","是否电影票风控","是否特殊场次购票","可使用专题","是否展示商品面值","号段","是否被冻结"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < list.size(); i++) {
                CardsBatch2 cardsBatch2 = list.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(cardsBatch2.getId());
                row.createCell(1).setCellValue(cardsBatch2.getSecondBantchNum());
                row.createCell(2).setCellValue(cardsBatch2.getFirstBatchNum());
                row.createCell(3).setCellValue(cardsBatch2.getCardType());
                row.createCell(4).setCellValue(cardsBatch2.getFaceValue());
                row.createCell(5).setCellValue(cardsBatch2.getSalePrice());
                row.createCell(6).setCellValue(cardsBatch2.getEnableCity());
                row.createCell(9).setCellValue(cardsBatch2.getIsFlimFk());
                row.createCell(10).setCellValue(cardsBatch2.getIsSpecialShowing());
                row.createCell(11).setCellValue(cardsBatch2.getSalesTopicId());
                row.createCell(12).setCellValue(cardsBatch2.getIsShowFacevalue());
                row.createCell(13).setCellValue(cardsBatch2.getParagraphNumber());
                row.createCell(14).setCellValue(cardsBatch2.getIsEnable());
                Cell createTimeCell = row.createCell(7);
                Cell updateTimeCell = row.createCell(8);
                LocalDateTime updatedTime = cardsBatch2.getUpdatedTime();
                updateTimeCell.setCellValue(updatedTime.format(formatter));
                createTimeCell.setCellValue(cardsBatch2.getCreateTime().format(formatter));
                CellStyle DateCellStyle = workbook.createCellStyle();
                DateCellStyle.setDataFormat(workbook.getCreationHelper()
                        .createDataFormat()
                        .getFormat("yyyy-MM-dd"));
                createTimeCell.setCellStyle(DateCellStyle);
            }
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("应收账款报表", "UTF-8") + ".xlsx");
            //保存Excel文件
            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);

            //关闭资源
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("导出文件成功!");
    }
}
